import './public-path'
import { createApp } from "vue";
import { createWebHistory, createRouter } from 'vue-router';
import App from "./App.vue";
import routes from "./router/index";
import store from "./store/index";

let instance:any= null, history:any="", router=null;

function render(props:any={}) {  
    // props 组件通信
    const { container } = props;
    history = createWebHistory(window.__POWERED_BY_QIANKUN__ ? '/test-app/' : process.env.VUE_APP_PATH);
    router = createRouter({
      history,
      routes,
    });
  
    instance = createApp(App);
    instance.use(router);
    instance.use(store);
    instance.mount(container ? container.querySelector('#test') : '#test');
}

if (!window.__POWERED_BY_QIANKUN__) {
    render();
  }  
  
  export async function bootstrap() {
    console.log('%c ', 'color: green;', 'vue3.0 app bootstraped');
  }
  
  function storeTest(props:any) {
    props.onGlobalStateChange &&
      props.onGlobalStateChange(
        (value: any, prev: any) => console.log(`[onGlobalStateChange - ${props.name}]:`, value, prev),
        true,
      );
    props.setGlobalState &&
      props.setGlobalState({
        ignore: props.name,
        user: {
          name: props.name,
        },
      });
  }
  
  export async function mount(props: any) {
    storeTest(props);
    render(props);
    instance.config.globalProperties.$onGlobalStateChange = props.onGlobalStateChange;
    instance.config.globalProperties.$setGlobalState = props.setGlobalState;
  }
  
  export async function unmount() {
    instance.unmount();
    instance._container.innerHTML = '';
    instance = null;
    router = null;
    history.destroy();
  }


